<?php
include(DIR_INCLUDE . 'mail.php');

$acttached_files = array();
$adir = md5( session_id() . (string)time() );

/* Upload attached files */
if( isset($_FILES['attached-file']) AND !empty($_FILES["attached-file"]['name'][0]) ) {
	mkdir(DIR_UPLOAD . 'attached_file/' . $adir);

	for($j=0; $j < count($_FILES["attached-file"]['name']); $j++) { 
		$filen = $_FILES["attached-file"]['name']["$j"];
		$path = DIR_UPLOAD . 'attached_file/' . $adir . '/' . $filen;

		if(move_uploaded_file($_FILES["attached-file"]['tmp_name']["$j"], $path)) {
			$acttached_files[] = $path;
		}
	}
}

/* Prepare receiver */

/* Send mail */
$mail = new Mail();

$mail->protocol = $g_config['protocol'];
$mail->hostname = $g_config['hostname'];
$mail->port = intval($g_config['port']);
$mail->username = $g_config['username'];
$mail->password = $g_config['password'];
$mail->timeout = intval($g_config['timeout']);

$mail->setSender($g_config['sender']);
$mail->setFrom($g_config['from']);

/* Người nhận */
if (isset($_POST['to'])) {
	$parsed_to = parseMixedContact($_POST['to']);
	$to = parseReceiver($parsed_to);
	$mail->setTo($to);	
}
// cc
if (isset($_POST['cc'])) {
	$parsed_cc = parseMixedContact($_POST['cc']);
	$cc = parseReceiver($parsed_cc);
	$mail->setCc($cc);
}
// bcc
if (isset($_POST['bcc'])) {
	$parsed_bcc = parseMixedContact($_POST['bcc']);
	$bcc = parseReceiver($parsed_bcc);
	$mail->setBcc($bcc);
}

// Kiểm tra người nhận
if (empty($to) AND empty($cc) AND empty($bcc)) {
	$_SESSION['send_success'] = false;
	$_SESSION['msg'] = 'Người nhận không chính xác!';

	session_write_close();
	header('Location: ' . URL . '?page=viet_mail');
}


/* Tiêu đề */
$mail->setSubject($_POST['subject']);

/* Nội dung */
$message = '';
// Kiểm tra loại mail
if ($_POST['mail_type'] == 'text') {

	$mail->setHTML($_POST['text_message']); // Send plain text

	$message = $_POST['text_message'];

} elseif ($_POST['mail_type'] == 'html') {

	// Get path of the selected web mail
	$sql = "SELECT web_mail_id, name, description, path FROM web_mail";
	$sql .= " WHERE web_mail_id='" . intval($_POST['web_mail_id']) . "'";
	$web_mail = mysql_fetch_assoc(mysql_query($sql)); 

	$web_mail_content = file_get_contents(DIR_UPLOAD . 'web_mail/' . $web_mail['path'] . '/index.html');

	$mail->setHTML($web_mail_content); // Send web mail

	$message = $web_mail_content;
}

/* Thêm tệp đính kèm */
foreach ($acttached_files as $file) {
	$mail->addAttachment($file);
}

/* Gửi mail */
if ($mail->send()) {
	$_SESSION['send_success'] = true;

	// Thêm mail đã gửi
	$sql = "INSERT INTO sent_mail(subject, message, sent_date, attached_dir) VALUES('%s', '%s', '%s', '%s')";
	$q = sprintf($sql, db_escape($_POST['subject']), db_escape($message), date('Y-m-d H:i:s'), (empty($acttached_files)? 'NULL': $adir) );
	$success  = mysql_query($q) OR _log('Error query: ' . $q);

	if ($success) {
		$mail_id = mysql_insert_id();

		// Thêm to
		addSentContact($mail_id, $parsed_to, 'to');

		// Thêm cc
		if (isset($parsed_cc)) {
			addSentContact($mail_id, $parsed_cc, 'cc');
		}

		// Thêm bcc
		if (isset($parsed_bcc)) {
			addSentContact($mail_id, $parsed_bcc, 'bcc');
		}
	}
} else {
	$_SESSION['send_success'] = false;
}

header('Location: ' . URL . '?page=mail_da_gui');